import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from torchvision import datasets
import torch.optim as optim
from torch.utils.data import DataLoader

transform = transforms.ToTensor()
train_set = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_set = datasets.MNIST('./data', train=False, transform=transform, download=True)

train_loader = DataLoader(dataset=train_set, batch_size=32, shuffle=True)
test_loader = DataLoader(dataset=test_set, batch_size=32, shuffle=True)


class ResidualBloch(nn.Module):
    def __init__(self, channel):
        super(ResidualBloch, self).__init__()
        self.channel = channel
        self.conv1 = nn.Conv2d(channel, channel, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(channel, channel, kernel_size=3, padding=1)

    def forward(self, x):
        y = F.relu(self.conv1(x))
        y = self.conv2(y)
        return F.relu(x + y)


class ResidualNet(nn.Module):
    def __init__(self):
        super(ResidualNet, self).__init__()
        self.conv1 = nn.Conv2d(1, 16, kernel_size=5)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=5)
        self.mp = nn.MaxPool2d(2)

        self.rblock1 = ResidualBloch(16)
        self.rblock2 = ResidualBloch(32)

        self.fc = nn.Linear(512, 10)

    def forward(self, x):
        in_size = x.size(0)
        x = self.mp(F.relu(self.conv1(x)))
        x = self.rblock1(x)
        x = self.mp(F.relu(self.conv2(x)))
        x = self.rblock2(x)
        x = x.view(in_size, -1)
        x = self.fc(x)
        return x

model = ResidualNet()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
print(f'使用设备:{device}')

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)


def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        input, target = data
        input, target = input.to(device), target.to(device)
        optimizer.zero_grad()
        outputs = model(input)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, batch_idx + 1, running_loss / 2000))
            running_loss = 0.0


def test():
    corret = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            input, target = data
            input, target = input.to(device), target.to(device)
            outputs = model(input)
            _, predict = torch.max(outputs.data, dim=1)
            total += target.size(0)
            corret += (predict == target).sum().item()
    print('Accuracy on test set: %d %% [%d/%d]' % (100 * corret / total, corret, total))


if __name__ == '__main__':
    for epoch in range(5):
        train(epoch)
    test()

